import 'dart:io';
import 'dart:math';

import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit_config.dart';
import 'package:ffmpeg_kit_flutter/return_code.dart';
import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lucide_icons/lucide_icons.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video2gif/app_theme.dart';
import 'package:video_player/video_player.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  final picker = ImagePicker();

  File? videoFile;

  File? gifOutputFile;

  VideoPlayerController? _videoPlayerController;

  int state = 0;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 1500));
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController?.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: Container(
          alignment: Alignment.center,
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [if (state == 0) wVideoPicker() else wFileOpt()],
            ),
          ),
        ),
      ),
    );
  }

  Widget wVideoPicker() {
    var screenSize = MediaQuery.of(context).size;
    return InkWell(
      onTap: () {
        _pickVideo();
      },
      child: Container(
        width: screenSize.width / 2,
        height: screenSize.width / 2,
        decoration: BoxDecoration(
            color: AppTheme.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                offset: Offset(4, 4),
                color: AppTheme.grey.withOpacity(0.3),
                blurRadius: 8,
              )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.add, size: 50),
            SizedBox(height: 10),
            Text("请选择文件"),
          ],
        ),
      ),
    );
  }

  Widget wFileOpt() {
    var screenSize = MediaQuery.of(context).size;
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          width: screenSize.width / 2,
          height: screenSize.width / 2,
          decoration: BoxDecoration(
            color: AppTheme.lightGrey,
            borderRadius: BorderRadius.circular(10),
          ),
          child: FittedBox(
            clipBehavior: Clip.hardEdge,
            child: SizedBox(
              width: _videoPlayerController!.value.size.width,
              height: _videoPlayerController!.value.size.height,
              child: VideoPlayer(_videoPlayerController!),
            ),
          ),
        ),
        Center(
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: optVideoFile,
            child: Container(
              width: 66,
              height: 66,
              decoration: BoxDecoration(
                  color: AppTheme.nearlyBlue.withOpacity(0.5),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      offset: Offset(8, 8),
                      blurRadius: 20,
                      color: AppTheme.grey.withOpacity(0.3),
                    )
                  ]),
              child: RotationTransition(
                turns: Tween(begin: 0.0, end: 1.0).animate(
                    CurvedAnimation(parent: _controller, curve: AxeCurve())),
                alignment: Alignment.centerLeft,
                child: Icon(state == 3
                    ? LucideIcons.download
                    : state == 4
                        ? LucideIcons.check
                        : LucideIcons.axe),
              ),
            ),
          ),
        )
      ],
    );
  }

  Future<void> _pickVideo() async {
    var pickedFile = await picker.pickVideo(source: ImageSource.gallery);
    if (pickedFile != null) {
      videoFile = File(pickedFile.path);
      _videoPlayerController = VideoPlayerController.file(videoFile!)
        ..initialize().then((_) {
          setState(() {
            //已选择视频
            state = 1;
          });
        });
    }
  }

  void optVideoFile() async {
    if (state == 2) {
      return null;
    } else if (state == 4) {
      setState(() {
        //初始化
        state = 0;
      });
    } else if (state == 3) {
      await GallerySaver.saveImage(gifOutputFile!.path);
      setState(() {
        //已保存gif到图库
        state = 4;
      });
    } else if (state == 1) {
      _controller.repeat();

      FFmpegKitConfig.enableLogCallback((log) {
        final message = log.getMessage();
        print(message);
      });
      final Directory directory = await getTemporaryDirectory();
      gifOutputFile = File('${directory.path}/output.gif');
      var session = await FFmpegKit.execute(
          "-y -i ${videoFile!.path} -r 5 ${gifOutputFile!.path}");
      setState(() {
        //视频处理中
        state = 2;
      });
      final returnCode = await session.getReturnCode();
      if (ReturnCode.isSuccess(returnCode)) {
        print('SUCCESS');
        setState(() {
          //已转换成gif
          state = 3;
          _controller.reset();
        });
      } else if (ReturnCode.isCancel(returnCode)) {
        print('CANCEL');
      } else {
        print('ERROR');
      }
    }
  }
}

class AxeCurve extends Curve {
  @override
  double transform(double t) {
    return -sin(t * 6.28) * 0.04;
  }
}
